package com.example.demo.service;

import com.example.demo.dao.GoodJPARepository;
import com.example.demo.entity.GoodsItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service
public class GoodService {
    @Autowired
    GoodJPARepository goodRepository;
    public GoodsItem addGood(GoodsItem good){
        return goodRepository.saveAndFlush(good);
    }
    public GoodsItem getGood(long id){
        return goodRepository.getById(id);
    }
    public void updateGood(long id,GoodsItem good){
        goodRepository.save(good);
    }
    public void deleteGood(long id){
        goodRepository.deleteById(id);
    }
    public List<GoodsItem> findGood(String name){
        //动态构造查询条件，name和complete不为null时作为条件
        Specification<GoodsItem> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> predicateList = new ArrayList<>();
            if (name != null) {
                predicateList.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
            }
            Predicate[] predicates = predicateList.toArray(new Predicate[predicateList.size()]);
            return criteriaBuilder.and(predicates);
        };

        List<GoodsItem> result= goodRepository.findAll(specification);
        return result;
    }

    public List<GoodsItem> findGoodByname(String name){
        return goodRepository.findByName(name);
    }
    public List<GoodsItem> findGoodByNameContaining(String name){
        return goodRepository.findByNameContaining(name);
    }
    public List<GoodsItem> findGoodByPriceBetween(double price1,double price2){
        return goodRepository.findByPriceBetween(price1,price2);
    }
    public List<GoodsItem> findGoodWithJPQLByName(String name){
        return goodRepository.findWithJPQLByName(name);
    }
    public List<GoodsItem> findGoodWithJPQLByNameandPrice(String name,double price){
        return goodRepository.findWithJPQLByNameAndPrice(name,price);
    }
}
